<?php
$sanitize_all_escapes = true;
$fake_register_globals = false;
if (!isset($_REQUEST['medico']))
    session_start();

$landingpage = "index.php?site=" . $_SESSION['site_id'];
if (isset($_SESSION['pid']) && isset($_SESSION['patient_portal_onsite'])) {
    $pid = $_SESSION['pid'];
} else {
    if (!isset($_REQUEST['medico'])) {
        session_destroy();
        header('Location: ' . $landingpage . '&w');
        exit;
    }
}
$medico = "";
$medicoIni = "";
$source_entry = "1";
$provider_id = "";
$provider_value = "";

$ignoreAuth = true;
require_once('../interface/globals.php');

include_once("$srcdir/sql.inc");
include_once("$srcdir/options.inc.php");
require_once("$srcdir/patient_provider.inc.php");

if (isset($_REQUEST['medico']))
    $pid = $_REQUEST['set_pid'];

if (isset($_REQUEST['medico'])) {
    $provider_id = "provider_id = ";
    $provider_value = "'" . add_escape_custom($_SESSION['authUserID']) . "',";
    $medico = "&medico=1&set_pid=" . $pid;
    $medicoIni = "?medico=1&set_pid=" . $pid;
    $source_entry = "0";
}

$query = "SELECT * FROM codes order by code_text ASC ";
$data = query_paciente($query);
$dataHTML = "";
if (sizeof($data) > 0) {
    foreach ($data as $valor) {
        $dataHTML .= "<option value='" . $valor["id"] . "'>" . $valor["code_text_short"] . "</option>";
    }
}

function query_paciente($query) {
    ob_start();
    $res = sqlStatement($query);
    if ($res) {
        for ($iter = 0; $row = sqlFetchArray($res); $iter++) {
            $all[$iter] = $row;
        }
    }
    $v = ob_get_clean();
    return $all;
}

if (isset($_GET['mode'])) {

    if ($_GET['mode'] == "add") {

        $sql = "REPLACE INTO immunizations set 
                      id = ?,
                      administered_date = if(?,?,NULL),  
                      immunization_id = ?,
                      immunization_name = ?,
                      cvx_code = ?, 
                      manufacturer = ?,
                      lot_number = ?,
                      administered_by_id = if(?,?,NULL),
                      administered_by = if(?,?,NULL),
                      education_date = if(?,?,NULL), 
                      vis_date = if(?,?,NULL), 
                      note   = ?,
                      patient_id   = ?,
                      created_by = ?,
                      updated_by = ?,
                      source_entry = '" . $source_entry . "',"
                . $provider_id . $provider_value . "
                      create_date = now() ";
        $sqlBindArray = array(
            trim($_GET['id']),
            trim(toDate($_GET['administered_date'])),
            trim(toDate($_GET['administered_date'])),
            trim($_GET['form_immunization_id']),
            trim($_GET['immunization_name']),
            trim($_GET['cvx_code']),
            trim($_GET['manufacturer']),
            trim($_GET['lot_number']),
            trim($_GET['administered_by_id']), trim($_GET['administered_by_id']),
            trim($_GET['administered_by']), trim($_GET['administered_by']),
            trim($_GET['education_date']), trim($_GET['education_date']),
            trim($_GET['vis_date']), trim($_GET['vis_date']),
            trim($_GET['note']),
            $pid,
            $_SESSION['authId'],
            $_SESSION['authId']
        );
        sqlStatement($sql, $sqlBindArray);
        $administered_date = $education_date = date('Y-m-d');
        $immunization_id = $cvx_code = $manufacturer = $lot_number = $administered_by_id = $note = $id = "";
        $administered_by = $vis_date = "";
    } elseif ($_GET['mode'] == "delete") {
        // log the event
        newEvent("delete", $_SESSION['authUser'], $_SESSION['authProvider'], 1, "Immunization id " . $_GET['id'] . " deleted from pid " . $pid);
        // delete the immunization
        $sql = "DELETE FROM immunizations WHERE id =? LIMIT 1";
        sqlStatement($sql, array($_GET['id']));
    } elseif ($_GET['mode'] == "edit") {
        $sql = "select * from immunizations where id = ?";
        $result = sqlQuery($sql, array($_GET['id']));
        $administered_date = $result['administered_date'];
        $immunization_id = $result['immunization_id'];
        $cvx_code = $result['cvx_code'];
        $code_text = '';
        if (!(empty($cvx_code))) {
            $query = "SELECT codes.code_text as `code_text`, codes.code as `code` " .
                    "FROM codes " .
                    "LEFT JOIN code_types on codes.code_type = code_types.ct_id " .
                    "WHERE code_types.ct_key = 'CVX' AND codes.code = ?";
            $result_code_text = sqlQuery($query, array($cvx_code));
            $code_text = $result_code_text['code_text'];
        }
        $manufacturer = $result['manufacturer'];
        $lot_number = $result['lot_number'];
        $administered_by_id = ($result['administered_by_id'] ? $result['administered_by_id'] : 0);
        $administered_by = $result['administered_by'];
        $education_date = $result['education_date'];
        $vis_date = $result['vis_date'];
        $note = $result['note'];

        //set id for page
        $id = $_GET['id'];
    }
    echo "<html><body><script language='JavaScript'>\n";
    echo " parent.$.fancybox.close();\n";

    echo "</script></body></html>\n";
    exit();
}

// Decide whether using the CVX list or the custom list in list_options
if ($GLOBALS['use_custom_immun_list']) {
    // user forces the use of the custom list
    $useCVX = false;
} else {
    if ($_GET['mode'] == "edit") {
        //depends on if a cvx code is enterer already
        if (empty($cvx_code)) {
            $useCVX = false;
        } else {
            $useCVX = true;
        }
    } else { // $_GET['mode'] == "add"
        $useCVX = true;
    }
}

// set the default sort method for the list of past immunizations
$sortby = $_GET['sortby'];
if (!$sortby) {
    $sortby = 'vacc';
}

// set the default value of 'administered_by'
if (!$administered_by && !$administered_by_id) {
    $stmt = "select concat(lname,', ',fname) as full_name " .
            " from users where " .
            " id=?";
    $row = sqlQuery($stmt, array($_SESSION['authId']));
    $administered_by = $row['full_name'];
}
?>
<html>
    <head>
        
        <!-- page styles -->
        <link rel="stylesheet" href="<?php echo $css_header; ?>" type="text/css">
        <link rel="stylesheet" href="css/nightingale.css" type="text/css"/>
        <link rel="stylesheet" href="css/datepickerImmunization.css" type="text/css"/>
        <link rel="stylesheet" href="<?php echo $GLOBALS['webroot'] ?>/library/js/redmond/jquery-ui-1.10.3.custom.min.css" type="text/css"/>


        <!-- supporting javascript code -->

        <script type="text/javascript" src="<?php echo $web_root; ?>/library/js/jquery-1.10.0.min.js"></script>

        <!--<script type="text/javascript" src="<?php echo $web_root; ?>/library/js/common.js"></script>
        <script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/textformat.js"></script>
        <script type="text/javascript" src="<?php echo $GLOBALS['webroot'] ?>/library/dialog.js"></script>
-->
        <script type="text/javascript" src="js/jquery.ui.core.js"></script>
        <script type="text/javascript" src="js/jquery.ui.widget.js"></script>
        <script type="text/javascript" src="js/jquery.ui.datepicker.js"></script>
        <script type="text/javascript" src="js/jquery.mask.min.js"></script>

        <style>
            .highlight {
                color: green;
            }
            tr.selected {
                background-color: white;
            }	
        </style>

       

        <script language="javascript">
           

            $(document).ready(function() {
                
                $("#cancel").click(function() {
                    parent.jQuery.fancybox.close();
                });
                
                $("#administered_date").datepicker({
                    showOn: "button",
                    buttonImage: "images/calendar-green.gif",
                    dateFormat: 'dd/mm/yy',
                    buttonImageOnly: true
                });
                $("#administered_date").mask("99/99/9999");

<?php if (!($useCVX)) { ?>
                    $("#save").click(function() {
                        SaveForm();
                    });
<?php } else { ?>
                    $("#save").click(function() {
                        if (validate_cvx()) {
                            SaveForm();
                        }
                        else {
                            return;
                        }
                    });
<?php } ?>
                $("#print").click(function() {
                    PrintForm("pdf");
                });
                $("#printHtml").click(function() {
                    PrintForm("html");
                });
                $(".immrow").click(function() {
                    EditImm(this);
                });
                $(".delete").click(function(event) {
                    DeleteImm(this);
                    event.stopPropagation();
                });

                $(".immrow").mouseover(function() {
                    $(this).toggleClass("highlight");
                });
                $(".immrow").mouseout(function() {
                    $(this).toggleClass("highlight");
                });

                $("#administered_by_id").change(function() {
                    $("#administered_by").val($("#administered_by_id :selected").text());
                });

                $("#form_immunization_id").change(function() {
                    if ($(this).val() != "") {
                        $("#cvx_code").val("");
                        $("#cvx_description").text("");
                        $("#cvx_code").change();
                    }
                });
            });

            var PrintForm = function(typ) {
                top.restoreSession();
                newURL = 'shot_record.php?output=' + typ + '&sortby=<?php echo $sortby; ?>';
                if (typ == "pdf") {
                    location.href = newURL;
                }
                else { // typ=html
                    window.open(newURL, '_blank', "menubar=1,toolbar=1,scrollbars=1,resizable=1,width=600,height=450");
                }
            }

            var SaveForm = function() {
//                top.restoreSession();
                if ($("#immunization_name").val() == "")
                    alert("<?php echo addslashes(xl('Please enter a title!')); ?>");
                else
                    $("#add_immunization").submit();
            }

            var EditImm = function(imm) {
                top.restoreSession();
                location.href = 'immunizations.php?mode=edit&id=' + imm.id;
            }

            var DeleteImm = function(imm) {
                if (confirm("<?php echo htmlspecialchars(xl('This action cannot be undone.'), ENT_QUOTES); ?>" + "\n" + "<?php echo htmlspecialchars(xl('Do you wish to PERMANENTLY delete this immunization record?'), ENT_QUOTES); ?>")) {
                    top.restoreSession();
                    location.href = 'immunizations.php?mode=delete&id=' + imm.id;
                }
            }

            //This is for callback by the find-code popup.
            //Appends to or erases the current list of diagnoses.
            function set_related(codetype, code, selector, codedesc) {
                var f = document.forms[0][current_sel_name];
                var s = f.value;

                if (code) {
                    s = code;
                }
                else {
                    s = '';
                }

                f.value = s;
                $("#cvx_description").text(codedesc);
                $("#form_immunization_id").attr("value", "");
                $("#form_immunization_id").change();
            }


            // This invokes the find-code popup.
            function sel_cvxcode(e) {
                current_sel_name = e.name;
                dlgopen('find_code_popup.php?codetype=CVX', '_blank', 500, 400);
            }

            // This ensures the cvx centric entry is filled.
            function validate_cvx() {
                if (document.add_immunization.cvx_code.value > 0) {
                    return true;
                }
                else {
                    document.add_immunization.cvx_code.style.backgroundColor = "red";
                    document.add_immunization.cvx_code.focus();
                    return false;
                }
            }

            var mypcc = '<?php echo htmlspecialchars($GLOBALS['phone_country_code'], ENT_QUOTES); ?>';
        </script>

    </head>

    <body class="body_top">

        <form action="immunizations.php" name="add_immunization" id="add_immunization">

            <div class="borde_normal">
                <span class="historial_paciente"><i style="font-size: 1.4em;" class="icon-pushpin"></i> <?php echo htmlspecialchars(xl('Immunizations'), ENT_NOQUOTES); ?> </span>
                                
                    <a href="" id="save" class="css_button" onclick="return false;"><span><i class="icon-ok-sign" style="font-size: 25px;"></i> <?php xl('Save', 'e'); ?></span></a>
                    <a href="" id="cancel" class="css_button"><span><i class="icon-remove-sign" style="font-size: 25px;"></i> <?php xl('Cancel', 'e'); ?></span></a>
                </tr>
            </div>

            <input type="hidden" name="mode" id="mode" value="add">
            <input type="hidden" name="id" id="id" value="<?php echo htmlspecialchars($id, ENT_QUOTES); ?>"> 
            <input type="hidden" name="pid" id="pid" value="<?php echo htmlspecialchars($pid, ENT_QUOTES); ?>"> 
            <input type="hidden" name="set_pid" id="set_pid" value="<?php echo htmlspecialchars($pid, ENT_QUOTES); ?>"> 
            <?php
            if (isset($_REQUEST['medico'])) {
                echo "<input type='hidden' name='medico' value='1'>\n";
            }
            ?>
            <br>
            <table border=0 cellpadding=1 cellspacing=1>

                <?php if (!($useCVX)) { ?>
                    <tr>
                        <td align="left">
                            <span class=text>
                                <?php echo htmlspecialchars(xl('Immunization'), ENT_NOQUOTES); ?>
                            </span>
                        </td>
                        <td>
                            <?php
                            // Modified 7/2009 by BM to incorporate the immunization items into the list_options listings
                            generate_form_field(array('data_type' => 1, 'field_id' => 'immunization_id', 'list_id' => 'immunizations', 'empty_title' => 'SKIP'), $immunization_id);
                            ?>
                        </td>
                    </tr>
                <?php } else { ?>
                    <tr>
                        <td align="right" valign="top" style="padding-top:4px;">
                            <span>
                                <?php echo htmlspecialchars(xl('Immunization'), ENT_NOQUOTES); ?>:
                            </span>
                        </td>
                        <td>
                            <select id="drpImmunization" name="cvx_code" class="">
                                <option value="-1">--Seleccione una opci&oacute;n--</option>
                                <?php echo $dataHTML; ?>
                            </select>
                            <!--<input type='hidden' size='255' name='cvx_code' id='cvx_code' value='99999999'/>--> 

                <!--                            <input type='text' size='255' name='immunization_name' id='immunization_name' style="width:450px;"
                title='Escriba un nombre para vacunaci&o&oacute;n'
                />-->
                            <div id='cvx_description' style='display:none; float:right; padding:3px; margin-left:3px; width:400px'>
                                <?php echo htmlspecialchars(xl($code_text), ENT_QUOTES); ?>
                            </div>
                        </td>
                    </tr>
                <?php } ?>

                <tr>
                    <td align="right" style="width: 120px;">
                        <span>
                            <?php echo htmlspecialchars(xl('Date Administered'), ENT_NOQUOTES); ?>:
                        </span>
                    </td>
                    <td>

                        <input type='text' size='10' name="administered_date" id="administered_date" class="my_datepicker"
                               value='<?php echo $administered_date ? htmlspecialchars($administered_date, ENT_QUOTES) : date('d/m/Y'); ?>'
                               title='dd-mm-aaaa'
                               />

                    </td>
                </tr>
                <tr style="display:none">
                    <td align="right">
                        <span class=text>
                            <?php echo htmlspecialchars(xl('Immunization Manufacturer'), ENT_NOQUOTES); ?>
                        </span>
                    </td>
                    <td>
                        <input class='text' type='text' name="manufacturer" size="25" value="<?php echo htmlspecialchars($manufacturer, ENT_QUOTES); ?>">
                    </td>
                </tr>
                <tr style="display:none">
                    <td align="right">
                        <span class=text>
                            <?php echo htmlspecialchars(xl('Immunization Lot Number'), ENT_NOQUOTES); ?>
                        </span>
                    </td>
                    <td>
                        <input class='text' type='text' name="lot_number" size="25" value="<?php echo htmlspecialchars($lot_number, ENT_QUOTES); ?>">
                    </td>
                </tr>
                <tr style="display:none">
                    <td align="right">
                        <span class='text'>
                            <?php echo htmlspecialchars(xl('Name and Title of Immunization Administrator'), ENT_NOQUOTES); ?>
                        </span>
                    </td>
                    <td class='text'>
                        <input type="text" name="administered_by" id="administered_by" size="25" value="<?php echo htmlspecialchars($administered_by, ENT_QUOTES); ?>">
                        <?php echo htmlspecialchars(xl('or choose'), ENT_NOQUOTES); ?>
                        <!-- NEEDS WORK -->
                        <select name="administered_by_id" id='administered_by_id'>
                            <option value=""></option>
                            <?php
                            $sql = "select id, concat(lname,', ',fname) as full_name " .
                                    "from users where username != '' " .
                                    "order by concat(lname,', ',fname)";

                            $result = sqlStatement($sql);
                            while ($row = sqlFetchArray($result)) {
                                echo '<OPTION VALUE=' . htmlspecialchars($row{'id'}, ENT_QUOTES);
                                echo (isset($administered_by_id) && $administered_by_id != "" ? $administered_by_id : $_SESSION['authId']) == $row{'id'} ? ' selected>' : '>';
                                echo htmlspecialchars($row{'full_name'}, ENT_NOQUOTES) . '</OPTION>';
                            }
                            ?>
                        </select>
                    </td>
                </tr>
                <tr style="display:none">
                    <td align="right" class="text">
                        <?php echo htmlspecialchars(xl('Date Immunization Information Statements Given'), ENT_NOQUOTES); ?>
                    </td>
                    <td>
                        <input type='text' size='10' name="education_date" id="education_date"
                               value='<?php echo $education_date ? htmlspecialchars($education_date, ENT_QUOTES) : date('Y-m-d'); ?>'
                               title='<?php echo htmlspecialchars(xl('yyyy-mm-dd'), ENT_QUOTES); ?>'
                               onkeyup='datekeyup(this, mypcc)' onblur='dateblur(this, mypcc);'
                               />
                        <img src='<?php echo $rootdir; ?>/pic/show_calendar.gif' align='absbottom' width='24' height='22'
                             id='img_education_date' border='0' alt='[?]' style='cursor:pointer;'
                             title='<?php echo htmlspecialchars(xl('Click here to choose a date'), ENT_QUOTES); ?>'
                             />
                    </td>
                </tr>
                <tr style="display:none">
                    <td align="right" class="text">
                        <?php echo htmlspecialchars(xl('Date of VIS Statement'), ENT_NOQUOTES); ?>
                        (<a href="http://www.cdc.gov/vaccines/pubs/vis/default.htm" title="<?php echo htmlspecialchars(xl('Help'), ENT_QUOTES); ?>" target="_blank">?</a>)
                    </td>
                    <td>
                        <input type='text' size='10' name="vis_date" id="vis_date"
                               value='<?php echo $vis_date ? htmlspecialchars($vis_date, ENT_QUOTES) : date('Y-m-d'); ?>'
                               title='<?php echo htmlspecialchars(xl('yyyy-mm-dd'), ENT_QUOTES); ?>'
                               onkeyup='datekeyup(this, mypcc)' onblur='dateblur(this, mypcc);'
                               />
                        <img src='<?php echo $rootdir; ?>/pic/show_calendar.gif' align='absbottom' width='24' height='22'
                             id='img_vis_date' border='0' alt='[?]' style='cursor:pointer;'
                             title='<?php echo htmlspecialchars(xl('Click here to choose a date'), ENT_QUOTES); ?>'
                             />
                    </td>
                </tr>
                <tr>
                    <td align="right" class='text'>
                        <?php echo htmlspecialchars(xl('Notes'), ENT_NOQUOTES); ?>
                    </td>
                    <td>
                        <textarea class='text' name="note" id="note" rows=3 cols=60><?php echo htmlspecialchars($note, ENT_NOQUOTES); ?></textarea>
                    </td>
                </tr>
            </table>
        </form>
    </body>
</html>
